package com.shanjupay.common.utilbak.apicommon;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.Reader;

public class JsonConvertObj {

    private static final Logger LOGGER = LoggerFactory.getLogger(JsonConvertObj.class);


    /**
     * 将请求的json串转换自定义对象
      * @param request
     * @param clazz
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> T convertRequestJson(HttpServletRequest request, Class<T> clazz)
            throws Exception
    {
        Reader reader = request.getReader();
        BufferedReader bufferReader = new BufferedReader(reader);

        StringBuilder sbuffer = new StringBuilder();

        String line = bufferReader.readLine();
        while (line != null) {
            sbuffer.append(line);
            line = bufferReader.readLine();
        }
        bufferReader.close();
        reader.close();

        String action = RequestTools.getAction(request);

        if(LOGGER.isInfoEnabled())
        {
            LOGGER.info("发起请求处理：{},请求处理参数：{}",action,sbuffer.toString());
        }

        T req = JsonTools.fromJson(sbuffer.toString(), clazz);
        return req;
    }

    /**
     * 将请求对象接送json字符串
     * @param request
     * @return
     * @throws Exception
     */
    public static String getReqestJonString(HttpServletRequest request)throws Exception
    {
        Reader reader = request.getReader();
        BufferedReader bufferReader = new BufferedReader(reader);

        StringBuilder sbuffer = new StringBuilder();

        String line = bufferReader.readLine();
        while (line != null) {
            sbuffer.append(line);
            line = bufferReader.readLine();
        }
        bufferReader.close();
        reader.close();


        return sbuffer.toString();
    }



}


